


#include <assert.h>
#include "UniqueString.h"
#include "AlgorithmHelper.h"

namespace FlameEngine
{
	std::unordered_map<uint64_t, std::shared_ptr<UniqueString>> UniqueString::s_uniqueStrings;
	std::mutex UniqueString::s_mutex;
	int32_t UniqueString::s_releaseCount = 0;

	std::shared_ptr<UniqueString> UniqueString::Create(const char* pStr)
	{
		uint64_t key = AlgorithmHelper::HashString(pStr);

		std::lock_guard<std::mutex> lock(s_mutex);
		auto it = s_uniqueStrings.find(key);
		if(it != s_uniqueStrings.end())
		{
			return it->second;
		}
		else
		{
			UniqueString* pNewStr = new UniqueString(key, pStr);
			auto& it = s_uniqueStrings.emplace(key, std::shared_ptr<UniqueString>(pNewStr));
			auto result = it.first->second;
			
			s_releaseCount++;
			if (s_releaseCount > 100)
			{
				ReleaseUnusedString();
				s_releaseCount = 0;
			}

			return result;
		}
	}

	UniqueString::UniqueString(uint64_t id, const char* str) :
		m_id(id),m_str(str)
	{
	}

	void UniqueString::ReleaseUnusedString()
	{
		for(auto it = s_uniqueStrings.begin();it!=s_uniqueStrings.end();)
		{
			if(it->second.unique())
				it = s_uniqueStrings.erase(it);
			else
				++it;
		}
	}
}